package com.amkai.aes.webservice.binary.objecthandler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.dictionary.SharedDictionaryManagerCommon;
import com.amkai.aes.aescommon.service.binary.job.checkexistence.CheckExistenceJob;
import com.amkai.aes.aescommon.service.binary.job.checkexistence.CheckExistenceParams;
import com.amkai.aes.aescommon.service.binary.job.checkexistence.CheckExistenceResult;
import com.amkai.aes.server.search.database.QueryGenerator;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class CheckExistenceHandler implements JobObjectHandler<CheckExistenceJob, CheckExistenceParams, CheckExistenceResult> {
	private static final Log logger = LogFactory.getLog(CheckExistenceHandler.class);
	
	
	private static final String ALL_QUERY =  " where it.id = :item_id AND it.kindWrapper.id = :item_itemKind ";
	private static final String NAME_QUERY = " where it.name = :item_name AND it.shortName = :item_shortname AND it.kindWrapper.id = :item_itemKind";


	@Override
	public CheckExistenceResult process(CheckExistenceJob job, CheckExistenceParams object) throws Exception {
		CheckExistenceResult result = null;
		SessionManager sm = null;
		try {
			sm = SiteManager.Start();
			sm.openSession();
			
			// KKORNEL: AES-11533
			String tableName = SharedDictionaryManagerCommon.getInstance().getItemClassName(object.getItemKind());
			
			String query = "";
			
			if (object.getId() != null)
				query = "SELECT it FROM " + tableName + " it " + ALL_QUERY;
			else
				query = "SELECT it FROM " + tableName + " it " + NAME_QUERY;
			
			if (object.getWhere() != null && object.getWhere().trim().length() > 0) {
				query += " AND " + object.getWhere() + " ";
			}
			
			
			Query hqlQuery = sm.execute(query);
			if (object.getId() != null) {
				hqlQuery.setParameter("item_id", object.getId());
				hqlQuery.setParameter("item_itemKind", object.getItemKind().ordinal());
			}
			else {
				hqlQuery.setParameter("item_name", object.getName());
				hqlQuery.setParameter("item_shortname", object.getShortName());
				hqlQuery.setParameter("item_itemKind", object.getItemKind().ordinal());
			}
			
			// KKORNEL: AES-6494
			QueryGenerator.applyHibernateArgsOnQuery(hqlQuery, object.getHibernateArgs());

			Object o = hqlQuery.uniqueResult();
			if( o != null ) {
				result = new CheckExistenceResult();
				result.setResult(o);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CheckExistence", e);
		}  finally {
			if( sm != null) {
				sm.closeSession();
			}
		}
		
		
		return result;
	}

	
	


}
